﻿using LightCAD.Core.Elements;
using LightCAD.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LightCAD.Runtime;
using LightCAD.MathLib;

namespace LightCAD.Drawing
{
    public class RefEditingObject : ElementSpace
    {
        public ViewportRuntime VportRt { get; set; }
        public LcBlockRef[] RefLinks { get; set; }
        public Matrix3[] RefMatrixes { get; set; }
        public Matrix3 TargetMatrix => RefMatrixes[this.Index];
        public LcBlockRef Target { get; set; }
        public int Index { get; set; }

        public void ElementsToWcs()
        {
            this.IsFireChangedEvent = false;
            foreach (var ele in Target.Block.Elements)
            {
                var copyEle = ele.Clone().ApplyMatrix(TargetMatrix);
                copyEle.Host = ele;
                this.InsertElement(copyEle);
                copyEle.PropertyChangedAfter += CopyEle_PropertyChangedAfter;
            }
            this.IsFireChangedEvent = true;
            this.ObjectChangedAfter += RefEditingObject_ObjectChangedAfter;
        }

        private void RefEditingObject_ObjectChangedAfter(object? sender, ObjectChangedEventArgs e)
        {
            var copyEle = e.Target as LcElement;
            if (e.Type == ObjectChangeType.Insert)
            {
                var cloneEle = copyEle.Clone().ApplyMatrix(TargetMatrix.Clone().Invert());
                this.Target.Block.InsertElement(cloneEle);
                copyEle.Host = cloneEle;
            }
            else
            {
                this.Target.Block.RemoveElement(copyEle.Host);
                copyEle.Host = null;
            }
        }

        private void CopyEle_PropertyChangedAfter(object? sender, PropertyChangedEventArgs e)
        {
            var copyEle = e.Object as LcElement;
            //将当前编辑复制元素，转换到在位编辑的元素坐标系
            var cloneEle = copyEle.Clone().ApplyMatrix(TargetMatrix.Clone().Invert());
            copyEle.Host.Copy(cloneEle);
            copyEle.Host.ResetBoundingBox();
        }

        public void SyncElements()
        {
            this.InsertElement(Target);
        }

        public void Dispose()
        {
        }


    }
}
